<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace plugins\lyz_kefu_chat\controller;

use think\Db;
use think\Config;
use cmf\controller\PluginBaseController;


class AdminIndexController extends PluginBaseController
{

    function _initialize()
    {
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        } else {
            //TODO no login
            $this->error('未登录');
        }
    }

    //workerman设置
    function index()
    {
        if($this->request->isPost()){  //编辑
            $data = [
                'option'    =>  json_encode(input('param.')),
            ];
            if(!empty($_POST['id'])){
                $fl = Db::name('plugin_lyz_kefu_chat_option_win')->where('id',$_POST['id'])->update($data);
                if($fl){
                    $this->success('更新成功');
                }else{
                    $this->error('更新失败');
                }
            }else{
                $fl = Db::name('plugin_lyz_kefu_chat_option_win')->insertGetId($data);
                if($fl){
                    $this->success('保存成功');
                }else{
                    $this->error('保存失败');
                }
            }
        }else{
            $list = Db::name('plugin_lyz_kefu_chat_option_win')->find();
            $arr = json_decode($list['option'],true);
            $this->assign('option',$arr['option']);
            $this->assign('list',$list);
        }
        return $this->fetch('/admin_workerman_set');
    }

    //workerman恢复默认
    function recover()
    {
        if($this->request->isPost()){  //编辑
            $list = Db::name('plugin_lyz_kefu_chat_option_win')->where('id',2)->find();
            $data = [
                'option'    => $list['option'],
            ];
            if(!empty($_POST['id'])){
                $fl = Db::name('plugin_lyz_kefu_chat_option_win')->where('id',$_POST['id'])->update($data);
                if($fl){
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    }

    //客服列表
    function kefuList()
    {
        $user_list = Db::name('plugin_lyz_kefu_chat_user_win')->select();
        $this->assign('user_list',$user_list);
        return $this->fetch('/admin_kefu_list');
    }

    //客服添加
    function kefuAdd()
    {
        if($this->request->isPost()){
            $data = [
               'user_name' => $_POST['user_name'],
                'user_nickname' => $_POST['user_nickname'],
               'user_status' => $_POST['user_status'],
               'client_id' => '',
               'user_pwd' => $_POST['user_pwd'],
               'create_time' => time(),
            ];
            //查询账号、名称是否存在
            $fl = Db::name('plugin_lyz_kefu_chat_user_win')->where('user_name',$_POST['user_name'])->find();
            $fl1 = Db::name('plugin_lyz_kefu_chat_user_win')->where('user_nickname',$_POST['user_nickname'])->find();
            if($fl || $fl1){
                $this->error("客服名称或者账号已经存在！");
            }else{
                $fl = Db::name('plugin_lyz_kefu_chat_user_win')->insertGetId($data);
                if($fl){
                    $this->success("客服添加成功！",cmf_plugin_url('LyzKefuChat://AdminIndex/kefuList'));
                }else{
                    $this->error("客服添加失败！");
                }
            }
        }
        return $this->fetch('/admin_kefu_add');
    }

    //客服信息编辑
    function kefuEdit()
    {
        if($this->request->isPost()){
            $data = [
                'user_name' => $_POST['user_name'],
                'user_nickname' => $_POST['user_nickname'],
                'user_status' => $_POST['user_status'],
                'user_pwd' => $_POST['user_pwd'],
                'user_id' => $_POST['user_id'],
            ];

            //查询账号是否已经存在
            $fl = Db::name('plugin_lyz_kefu_chat_user_win')->where('user_name',$_POST['user_name'])->where('user_id','<>',$_POST['user_id'])->find();
            $fl1 = Db::name('plugin_lyz_kefu_chat_user_win')->where('user_nickname',$_POST['user_nickname'])->where('user_id','<>',$_POST['user_id'])->find();
            if($fl || $fl1){
                $this->error("客服名称或者账号已经存在！");
            }
            $fl = Db::name('plugin_lyz_kefu_chat_user_win')->update($data);
            if($fl){
                $this->success("客服修改成功！",cmf_plugin_url('LyzKefuChat://AdminIndex/kefuList'));
            }else{
                $this->error("客服修改失败！");
            }
        }else{
            $user_id = input('param.user_id');
            if(!empty($user_id)){
                $user_list = Db::name('plugin_lyz_kefu_chat_user_win')->where('user_id',$user_id)->find();
                $this->assign('user_list',$user_list);
            }else{
                $this->error("请求出错！");
            }
        }
        return $this->fetch('/admin_kefu_edit');
    }

    //客服信息删除
    function kefuDel()
    {
        $user_id = input('param.user_id');
        //查询名称是否已经存在
        $fl = Db::name('plugin_lyz_kefu_chat_user_win')->where('user_id',$user_id)->delete();
        if($fl){
            $this->success("客服信息删除成功！",cmf_plugin_url('LyzKefuChat://AdminIndex/kefuList'));
        }else{
            $this->error("客服信息删除失败！");
        }

    }

    //服务启动与关闭状态查看
    function status()
    {
        if(strpos(strtolower(PHP_OS), 'win') === 0)
        {
            //win环境
            $data['php_os'] = 'win';
        }else{
            $data['php_os'] = 'linux';
        }
        $option = Db::name('plugin_lyz_kefu_chat_option_win')->find();
        $option = json_decode($option['option'],true);
        $option = $option['option'];

        $arr1 = [];
        @exec("C:\Windows\System32\\tasklist.exe",$arr);     //运行tasklist.exe,返回一个数组$arr
        foreach($arr as $value) {
            $list = explode(" ", $value);
            $arr1[] = $list[0];
            //查找指定进程并打印
            /* if('php.exe'==$list[0]){
                echo $info[0].'<br />';
            } */
        }
        $arr1 = array_search('php.exe',$arr1);
        $data['php_version'] = PHP_VERSION;  //php版本
        $data['workerman_version'] = '3.5.1';  //workerman版本
        $data['register'] = $option['register'];  //workerman版本
        $data['gateway'] = $option['gateway'];  //gateway进程
        $data['gateway_processes_name'] = $option['gateway_processes_name'];  //gateway名称
        $data['gateway_processes_num'] = $option['gateway_processes_num'];  //gateway进程数目
        $data['inner_ip'] = $option['inner_ip'];  //gateway 内网分布ip
        $data['gateway_start_port'] = $option['gateway_start_port'];  //gateway 开始端口
        $data['worker_processes_name'] = $option['worker_processes_name'];  //worker 名称
        $data['worker_processes_num'] = $option['worker_processes_num'];  //worker 进程数目
        if(!empty($arr1)){  //证明已经开启进程
            $data['status'] = 1;  //证明进程开启
        }else{
            $data['status'] = -1; //进程未开启
        }
        $this->assign('data',$data);
        //echo array_search("php.exe",$data);
        return $this->fetch('/admin_workerman_status');
        /*if(strpos(strtolower(PHP_OS), 'win') === 0)
        {
            exit("start.php not support windows, please use start_for_win.bat\n");
        }

        // 检查扩展
        if(!extension_loaded('pcntl'))
        {
            exit("Please install pcntl extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
        }

        if(!extension_loaded('posix'))
        {
            exit("Please install posix extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
        }*/
        /*$list = Db::name('plugin_lyz_kefu_chat_option_win')->find();
        $arr = json_decode($list['option'],true);
        // register 服务必须是text协议
        $register = new Register($arr['option']['register']);

        // gateway 进程
        $gateway = new Gateway($arr['option']['gateway']);
        // 设置名称，方便status时查看
        $gateway->name = $arr['option']['gateway_processes_name'];
        // 设置进程数，gateway进程数建议与cpu核数相同
        $gateway->count = $arr['option']['gateway_processes_num'];
        // 分布式部署时请设置成内网ip（非127.0.0.1）
        $gateway->lanIp = '127.0.0.1';
        // 内部通讯起始端口，假如$gateway->count=4，起始端口为4000
        // 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口
        $gateway->startPort = $arr['option']['gateway_start_port'];
        // 心跳间隔
        $gateway->pingInterval = $arr['option']['pingInterval'];
        // 心跳数据
        $gateway->pingData = $arr['option']['pingdata'];
        // 服务注册地址
        $gateway->registerAddress = $arr['option']['register'];

        // bussinessWorker 进程
        $worker = new BusinessWorker();
        // worker名称
        $worker->name = $arr['option']['worker_processes_name'];
        // bussinessWorker进程数量
        $worker->count = $arr['option']['worker_processes_num'];
        // 服务注册地址
        $worker->registerAddress = $arr['option']['register'];

        Worker::runAll(); //运行服务*/

        /*
        // 当客户端连接上来时，设置连接的onWebSocketConnect，即在websocket握手时的回调
        $gateway->onConnect = function($connection)
        {
            $connection->onWebSocketConnect = function($connection , $http_header)
            {
                // 可以在这里判断连接来源是否合法，不合法就关掉连接
                // $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
                if($_SERVER['HTTP_ORIGIN'] != 'http://chat.workerman.net')
                {
                    $connection->close();
                }
                // onWebSocketConnect 里面$_GET $_SERVER是可用的
                // var_dump($_GET, $_SERVER);
            };
        };
        */
    }
}
